/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-21 10:06:56
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-02 14:11:06
 * @FilePath: \vite-project\src\layout\LoginPage.tsx
 */
import { Tabs, Form, Input, Button, type TabsProps, Space } from 'antd';
import { Icon } from '@iconify/react';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom-v5-compat';
import { login, loginByMoobile, sendLoginSmsCode } from 'apis/common';
import CountDown from 'components/common/CountDown';
// import logoSvg from 'assets/login/logo.svg';
import { validateMobile } from 'utils/helper';
import PictureCode from 'components/common/PictureCode';
import CommonFooter from 'components/common/CommonFooter';
import loginBg2 from 'assets/login/login2.jpg';
import { LogoIcon } from 'icons';
import { useTokenStore } from '../store/user';

export default function LoginPage() {
    const [form] = Form.useForm();
    const items: TabsProps['items'] = [
        { key: '1', label: '账户登录' },
        { key: '2', label: '短信登录' },
    ];
    const [active, setActive] = useState('1');
    const { setToken, setExpireAt } = useTokenStore();
    const navigate = useNavigate();
    const [loading, setLoading] = useState<boolean>(false);
    const [refreshTime, setRefreshTime] = useState(0);

    const onSend = (callback: () => void) => {
        form.validateFields(['userName']).then((formdata) => {
            setLoading(true);
            sendLoginSmsCode({
                userName: formdata?.userName,
            })
                .then(() => {
                    callback?.();
                })
                .finally(() => {
                    setLoading(false);
                });
        });
    };

    // methods
    const onFinish = async (formData: API.LoginRequestType) => {
        setLoading(true);
        try {
            if (active === '2') {
                const res = await loginByMoobile(formData);
                setToken(res?.token);
                setExpireAt(res?.expireAt);
                navigate('/');
            } else {
                const res = await login({
                    ...formData,
                    picKey: formData.code?.picKey,
                    picCaptcha: formData.code?.picCaptcha,
                    code: void 0,
                });
                setToken(res?.token);
                setExpireAt(res?.expireAt);
                navigate('/database');
            }
        } catch (error) {
            if (error?.rspCode === '100061') {
                // 图形验证码错误 - 刷新验证码
                console.log('100061',error);
                setRefreshTime(new Date().getTime());
            }
        } finally {
            setLoading(false);
        }
    };
    const onChange = (key: string) => {
        const userName = form.getFieldValue('userName');
        if (userName) {
            form.validateFields(['userName']);
        }
        setActive(key);
    };

    return (
        <div className='w-full h-screen relative overflow-hidden green-gradient-to-right'>
            <img className='absolute z-1 w-2/3 top-0 left-0 h-full object-cover' src={loginBg2} alt='bg' />

            <div className='w-380px absolute z-3 top-[40%] left-[70%] -translate-x-[50%] -translate-y-[50%] backdrop-wrap rounded-4px py-32px px-40px'>
                <div className='relative'>
                    <LogoIcon />
                    <span className='absolute left-110px top-2px text-gray text-14px'>废钢无人质检系统</span>
                </div>
                <Tabs centered accessKey={active} items={items} onChange={onChange} size='large' />
                {/* 账户登录 */}
                <Form
                    className='mt-20px'
                    name='basic'
                    form={form}
                    wrapperCol={{ span: 24 }}
                    style={{ maxWidth: 600 }}
                    onFinish={onFinish}
                    autoComplete='off'
                >
                    {active === '1' ? (
                        <>
                            <Form.Item<API.LoginRequestType>
                                name='userName'
                                rules={[{ required: true, message: '请输入用户名' }]}
                            >
                                <Input
                                    prefix={<Icon className='text-20px' icon='icon-park-twotone:user' />}
                                    placeholder='用户名/手机号'
                                    size='large'
                                />
                            </Form.Item>
                            <Form.Item<API.LoginRequestType>
                                name='passwd'
                                rules={[{ required: true, message: '请输入密码' }]}
                            >
                                <Input.Password
                                    prefix={<Icon className='text-20px' icon='icon-park-twotone:lock' />}
                                    placeholder='密码'
                                    size='large'
                                />
                            </Form.Item>
                            <Form.Item name='code' rules={[{ required: true, message: '请输入验证码' }]}>
                                <PictureCode refreshTime={refreshTime} />
                            </Form.Item>
                        </>
                    ) : (
                        <>
                            <Form.Item<API.LoginRequestType>
                                name='userName'
                                rules={[
                                    { required: true, message: '请输入手机号' },
                                    () => ({
                                        validator: validateMobile,
                                    }),
                                ]}
                            >
                                <Input
                                    prefix={<Icon className='text-20px' icon='icon-park-twotone:phone' />}
                                    placeholder='手机号'
                                    size='large'
                                />
                            </Form.Item>
                            <Form.Item<API.LoginRequestType>
                                name='smsCode'
                                rules={[{ required: true, message: '请输入验证码' }]}
                            >
                                <div className='flex'>
                                    <Input.Password
                                        prefix={<Icon className='text-20px' icon='icon-park-twotone:key-two' />}
                                        placeholder='验证码'
                                        size='large'
                                        className='flex-1 mr-12px'
                                    />
                                    <CountDown onSend={onSend} loading={loading} />
                                </div>
                            </Form.Item>
                        </>
                    )}
                    <Form.Item>
                        <Button
                            loading={loading}
                            className='w-full mt-20px'
                            type='primary'
                            htmlType='submit'
                            size='large'
                        >
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {/* footer */}
            <div className='backdrop-wrap absolute z-2 bottom-0 w-full text-center text-14px'>
                <CommonFooter />
            </div>
        </div>
    );
}
